import React, { useEffect, useState } from 'react'
import { Swiper, NavBar, Space, Card, Tabs, Popup, Button, DotLoading } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import { MoreOutline, CloseOutline } from 'antd-mobile-icons'
import HomeStyle from './Home.module.css'
import Tabbar1 from '../../components/TabBar/TabBar.jsx'
import './lun.css'
import Avatar from './Avatar.jsx'
import axios from '../../util/axios.config'
import Icon from './icon'
import { get } from 'lodash'


axios.defaults.baseURL = 'http://47.116.116.42:3000/'
import { useDispatch, useSelector } from 'react-redux'

export default function Home() {

  const navigate = useNavigate()
  const img = ['./images/u23.jpg', './images/1.webp', './images/2.jpg', './images/4.webp']
  const img2 = ['./images/11.jpg', './images/22.webp', './images/33.jpg', './images/u387.png',]
  const list = [{ label: '点评高分', value: '1' },
  { label: '销量优先', value: '2' },
  { label: '上新菜品', value: '3' },
  { label: '10元以下', value: '4' }]

  const [visible4, setVisible4] = useState(false)
  const [foodList, setFoodList] = useState([])
  const [isShow, setShow] = useState(true)
  const [num, setNum] = useState(4)

  const [shopList, setShopList] = useState([])
  const [originalFoodList, setOriginalFoodList] = useState([]);


  // 排序函数
  const handlePai = (e) => {
    let sortedFoodList;
    switch (e) {
      //高分
      case '1':
        sortedFoodList = [...originalFoodList].sort((a, b) => b.score - a.score);
        break;
      case '2':
        // 月销
        sortedFoodList = [...originalFoodList].sort((a, b) => b.monthsale - a.monthsale);
        break;
      case '3':
        // 上新  默认排序
        sortedFoodList = [...originalFoodList];
        break;
      case '4':
        //10元以内
        sortedFoodList = originalFoodList.filter(item => item.price <= 10);
        break;
      default:
        sortedFoodList = [...originalFoodList];
    }
    setFoodList(sortedFoodList);
  };


  const handleTabChange = (e) => {
    // 重置 foodList 到初始状态
    setFoodList(originalFoodList);
    // 处理选项卡切换
    handlePai(e);

    // 处理动画
    let animation = document.querySelectorAll('#animation');
    let fooditem = document.querySelectorAll('#fooditem');

    function toggleClass(el, cls) {
      el.classList.remove(cls)// 移除class
      setTimeout(() => {
        el.classList.add(cls)
      }, 0)
    }

    // 修改为使用函数来操作className
    animation.forEach((item) => {
      toggleClass(item, 'slide-in-right')
    })

    fooditem.forEach((item) => {
      toggleClass(item, HomeStyle.fooditem)
    })
  }


  const right = (
    <div style={{ fontSize: 24 }}>
      <Space style={{ '--gap': '16px' }}>
        <MoreOutline />
      </Space>
    </div>
  )
  const getFood = async () => {
    let { data: { data } } = await axios.get('/food/fd')
    setOriginalFoodList(data);
    setFoodList(data)
  }
  //商店
  const getShop = async () => {
    let { data: { data } } = await axios.get('/food/shop')
    setShopList(data)

  }
  useEffect(() => {
    getFood()
    getShop()
  }, [])

  // 防抖函数
  function debounce(fn, delay) {
    let timer = null;
    return function () {
      const context = this;
      const args = arguments;
      clearTimeout(timer);
      timer = setTimeout(() => {
        fn.apply(context, args);
      }, delay);
    };
  }

  // 触底加载 // 防抖
  window.onscroll = debounce(function () {
    if (foodList.length <= num) return setShow(false)
    if (window.innerHeight + window.scrollY >= document.body.scrollHeight - 10) {
      setShow(true)
      const timer = setTimeout(() => {
        setNum(num + 4)
        setShow(false)
        clearTimeout(timer)
      }, 500)
    }
  }, 500)




  return (
    <div className={HomeStyle.home}>

      <div className={HomeStyle.top}>
        <NavBar backArrow={false} right={right}>
          <h4>校园外卖</h4>
        </NavBar>
      </div>


      <div className={HomeStyle.lun} id='lun'>
        <Swiper loop   >
          {img.map((item, index) => (
            <Swiper.Item key={index} style={{ height: '50vh' }}>
              <img src={item} alt="" style={{ width: '100%', height: '100%' }} />
            </Swiper.Item>
          ))}
        </Swiper>

      </div>
      <div className={HomeStyle.usercard}>
        <Avatar></Avatar>
      </div>


      <div >


        <div className={HomeStyle.appcard}>
          <div className={HomeStyle.cardone}>
            <div className={HomeStyle.ic} onClick={() => { navigate('/home/restaurant') }}>
              <Icon type="icon--canting"></Icon>
              <p>桃园</p>

            </div >
            <div className={HomeStyle.ic}>
              <Icon type="icon--canting"></Icon>
              <p>梨园</p>
            </div>
            <div className={HomeStyle.ic}>
              <Icon type="icon--canting"></Icon>
              <p>莘园</p>
            </div>

          </div>

          <div className={HomeStyle.cardtwo}>
            <div className={HomeStyle.ic}>
              <Icon type="icon-a-shangdiandianpu"></Icon>
              <p>商店</p>

            </div >
            <div className={HomeStyle.ic}>
              <Icon type="icon-naicha"></Icon>
              <p>奶茶店</p>
            </div>
            <div className={HomeStyle.ic}>
              <Icon type="icon-mianbaolingshishipintiantianquan"></Icon>
              <p>零食店</p>
            </div>
            <div className={HomeStyle.ic} onClick={() => navigate('/home/berider')}>
              <Icon type="icon-Icon_qishouyunying"></Icon>
              <p>成为骑手</p>
            </div>

          </div>



        </div>

      </div>
      <Swiper className={HomeStyle.lun1} loop autoplay >
        {img2.map((item, index) => (
          <Swiper.Item key={index} style={{ height: '13vh' }}>
            <img src={item} alt="" style={{ width: '90%', height: '100%' }} />
          </Swiper.Item>
        ))}
      </Swiper>

      <div className={HomeStyle.tab}>
        <Tabs defaultActiveKey={''} onChange={(e) => {
          handleTabChange(e)
        }}>
          {list.map((item) => <Tabs.Tab key={item.value} title={item.label} />)}
        </Tabs>
        <div
          onClick={() => {
            setVisible4(true)
          }}
        >
          <p id='more'>更多》</p>
        </div>
        <Popup
          visible={visible4}
          onMaskClick={() => {
            setVisible4(false)
          }}
          position='right'
          bodyStyle={{ width: '65vw' }}
        >
          <div className={HomeStyle.shoplist}>
            {shopList.map((item) =>
              <div key={item._id} className={HomeStyle.shopitem}>

                <Button color='warning' onClick={() => {

                }}>{item.name}</Button>
              </div>
            )}
          </div>
        </Popup>
      </div>
      {/* 食物列表 */}

      <div className={HomeStyle.food} >
        {foodList.slice(0, num).map((item) =>
          <div id='animation' className='slide-in-right' key={item._id}>
            <div id='fooditem' className={HomeStyle.fooditem} onClick={() => {
              navigate(`/shop/${item._id}`)
            }} >

              <img src={item.img} className={HomeStyle.img} alt="" />
              <h3 style={{ textAlign: 'left', marginLeft: '10px' }}>{item.name}</h3><br />
              <div style={{ display: 'flex' }}>
                <h2 style={{ marginLeft: '5px' }}>￥{item.price}</h2>
                <p className={HomeStyle.span}>月销:{item.monthsale}</p>


              </div>
            </div>


          </div>)}
      </div>


      <div className={HomeStyle.listloading}>
        {isShow ? <div>加载中<DotLoading /></div> : <div>没有更多数据了</div>}
      </div>
      <div style={{ height: '10vh' }}>

      </div>


      <Tabbar1 className="publicTabbar"></Tabbar1>
    </div>
  )
}


